<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      mode="default"
    />
    <Editor
      style="height: 300px; overflow-y: hidden"
      v-model="content"
      :defaultConfig="editorConfig"
      mode="default"
      @onCreated="handleCreated"
      @onChange="onChange"
    />
  </div>
</template>

<script setup name="WangEditor">
import "@wangeditor/editor/dist/css/style.css";
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();
const props = defineProps({
  /* 编辑器的内容 */
  modelValue: {
    type: String,
  },
});

const emit = defineEmits();
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const content = ref("");

watch(
  () => props.modelValue,
  (v) => {
    if (v !== content.value) {
      content.value = v === undefined ? "" : v;
    }
  },
  { immediate: true }
);

const toolbarConfig = {
  excludeKeys: [
    "todo",
    "emotion",
    "group-video",
    "codeBlock",
    "insertImage",
    "insertTable",
  ],
};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      fieldName: "file",
      maxFileSize: 100 * 1024 * 1024, // 100MB
      server: import.meta.env.VITE_APP_BASE_API + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 自定义插入图片
      customInsert(res, insertFn) {
        if (res.code == 200) {
          let fileUrl =
            window.location.origin +
            import.meta.env.VITE_APP_BASE_API +
            res.fileName;
          insertFn(fileUrl, res.originalFilename, fileUrl);
          // insertFn(res.url, res.originalFilename, res.url);
        } else {
          proxy.$modal.msgError(res.msg);
        }
      },
    },
  },
};

onMounted(() => {
  handleCreated();
});
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = Object.seal(editor);
};
// 获取编辑器最新内容
const onChange = (editor) => {
  const regex = new RegExp(`^[<p><br></p>]+$`);
  if (regex.test(editor.getHtml())) {
    emit("update:modelValue", "");
  } else {
    emit("update:modelValue", editor.getHtml());
  }
};
</script>
<style>
/* ::v-deep .w-e-text-container {
  height: 300px !important;
}
.w-e-text-container .w-e-scroll {
  height: 350px !important;
  -webkit-overflow-scrolling: touch;
} */
</style>
